package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dto.AdUserDTO;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dto.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //校验参数
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名或者密码不能为空");
        }
        //根据用户查询与用户信息
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "数据已存在");
        }
        //对比用户输入的密码  和  数据库中的密码是否一致
        String input = DigestUtils.md5DigestAsHex((password + adUser.getSalt()).getBytes(StandardCharsets.UTF_8));
        if (!input.equalsIgnoreCase(adUser.getPassword())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "输入密码错误");
        }
        //检查用户状态
        int status = adUser.getStatus().intValue();
        if (status != 9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //修改最近loginTime
        adUser.setLoginTime(new Date());
        this.updateById(adUser);
        //颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        //封装返回结果  data:{token : "", user : {} }
        Map result = new HashMap<>();
        result.put("token", token);
        // 敏感信息  所有封装 vo 返回结果  将adUser的属性拷贝到vo中
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(adUser, adUserVO);
        result.put("user", adUserVO);
        return ResponseResult.okResult(result);
    }
}
